package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import javax.crypto.spec.IvParameterSpec;

import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;

public class FullscreenActivity extends Activity {
	String analysisorigin = "";
	boolean editmode = false;
	boolean erasemode = false;
	boolean markersmode = false;

	public Bitmap originalBmp; // origin
	public static Bitmap activeBmp; // edited image
	public static Bitmap takenBmp;

	public static String origin;

	public Button btEdit;

	public static ArrayList<ConnectedComponent> componentlist = new ArrayList<ConnectedComponent>();
	public static ArrayList<ConnectedComponent> markerlist = new ArrayList<ConnectedComponent>();

	// menu items
	public Menu menu;

	//16 September for isntructions
	String doNotShow = "Show";
	
	public Bitmap getOriginalBmp() {
		return originalBmp;
	}

	// public static Bitmap getActiveBmp() {
	// return activeBmp;
	// }

	public void setOriginalBmp(Bitmap bmp) {
		originalBmp = bmp;
	}

	public static ArrayList<ConnectedComponent> getComponentlist() {
		return componentlist;
	}

	public static ArrayList<ConnectedComponent> getMarkerlist() {
		return markerlist;
	}

	//
	public TouchImageView imgView;
	public ArrayList<float[]> circlelist = new ArrayList<float[]>();

	//
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fullscreenactivity);
		
		
		
		

		if (getIntent().hasExtra("analysisorigin")) {
			analysisorigin = getIntent().getStringExtra("analysisorigin");
		}
		
		if(analysisorigin.equals("DNA")){
			// instructions
			String donotshow = "";
			final Dialog instructiondialog = new Dialog(FullscreenActivity.this);
			instructiondialog.setContentView(R.layout.instructiondialog);
			instructiondialog.setTitle("Attention");
			instructiondialog.setCancelable(true);
			instructiondialog.setCancelable(false);

			TextView tvInstructions = (TextView) instructiondialog
					.findViewById(R.id.tvInstructions);
			ImageView dialogIvImage = (ImageView) instructiondialog
					.findViewById(R.id.ivInstructions);
			final CheckBox donotshowbox = (CheckBox) instructiondialog.findViewById(R.id.donotshow);
			Button btOk = (Button) instructiondialog.findViewById(R.id.btOk);

			final SharedPreferences donotshowinstructions = this.getSharedPreferences(
					"instructions", 0);
			donotshow = donotshowinstructions.getString("dnafullscreeninstruction",
					"nothing");
			if (donotshow.equals("nothing")) {
				donotshow = "Show";
			}

			if (donotshow.equals("Show")) {
				tvInstructions.setText("Please draw at least 3 markers to allow the comparison of fragments");
				
				Drawable drawable = getResources().getDrawable(R.drawable.markeredit_instruction);

				Bitmap instructionbmp = ((BitmapDrawable)drawable).getBitmap();
				
				dialogIvImage.setImageBitmap(instructionbmp);
				
				instructiondialog.show();

				btOk.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(donotshowbox.isChecked()){
							SharedPreferences.Editor editor = donotshowinstructions.edit();
							editor.putString("dnafullscreeninstruction", "DoNotShow");
							editor.commit();
						}
						else
						{
							SharedPreferences.Editor editor = donotshowinstructions.edit();
							editor.putString("dnafullscreeninstruction", "Show");
							editor.commit();
						}
						instructiondialog.dismiss();
					}
				});
				
			}
			//
		}

		// get componentlist from segmentation activity
		if (getIntent().hasExtra("componentlist")) {
			componentlist = (ArrayList<ConnectedComponent>) getIntent()
					.getSerializableExtra("componentlist");

		}
		if (getIntent().hasExtra("markerlist")) {
			markerlist = (ArrayList<ConnectedComponent>) getIntent()
					.getSerializableExtra("markerlist");

		}

		if (getIntent().hasExtra("origin")) {
			origin = getIntent().getStringExtra("origin");
		}

		byte[] byteArray = getIntent().getByteArrayExtra("BMP");
		// 15/8
		Bitmap colorBmp = RotationActivity.colorBmp;
		originalBmp = colorBmp;
		// for discard changes
		byte[] byteArray2 = getIntent().getByteArrayExtra("BMP2");
		//activeBmp = BitmapFactory.decodeByteArray(byteArray, 0,
		//		byteArray.length);

		imgView = new TouchImageView(this, originalBmp, activeBmp);
		imgView.setMaxZoom(8f);

		setContentView(imgView);
		
		/*
		if(analysisorigin.equals("DNA")){
			 //set up dialog
            Dialog dialog = new Dialog(FullscreenActivity.this);
            dialog.setContentView(R.layout.instructiondialog);
            dialog.setTitle("Attention!");
            TextView text = (TextView) dialog.findViewById(R.id.textView1);
            text.setText("Please add three standard markers, "
            		+ "first click the options menu and then choose 'Edit markers'");
            ImageView ivImage = (ImageView)dialog.findViewById(R.id.ivImage);
            //set instructional image
            Button okBut = (Button)dialog.findViewById(R.id.btOk);
            CheckBox donotshow = (CheckBox)dialog.findViewById(R.id.donotshow);
            okBut.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
				}
			});
			
            
           
            

		}
		*/

		// LinearLayout myLayout = (LinearLayout)
		// findViewById(R.id.fullscreenactivitylayout2);
		// myLayout.addView(imgView);
		// imgView.invalidate();
		// myLayout.invalidate();
		// setContentView(myLayout);

		// TouchImageView vOne = (TouchImageView)findViewById(R.id.imgview);
		// vOne.originalBmp = originalBmp;
		// vOne.activeBmp = activeBmp;
		// vOne.setMaxZoom(8f);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu1) {
		// TODO Auto-generated method stub
		this.menu = menu1;
		getMenuInflater().inflate(R.menu.editmenu, menu1);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.btEdit:
			if (editmode == false) {
				editmode = true;
				// change to alternate
				item.setTitle("Stop");
				imgView.setEditMode(editmode);

				// when editing all other functions to false
				// erase
				MenuItem EraseBut = menu.findItem(R.id.btErase);
				EraseBut.setTitle("Erase");
				erasemode = false;
				imgView.setEraseMode(erasemode);
				//
				// markers
				MenuItem MarkersBut = menu.findItem(R.id.btMarkers);
				MarkersBut.setTitle("Add markers");
				markersmode = false;
				imgView.setMarkersmode(markersmode);
				//
			} else {
				// if click on stop, stop editing
				item.setTitle("Edit");
				editmode = false;
				imgView.setEditMode(editmode);

			}

			break;
		case R.id.btUndo:
			imgView.undoTemp();
			break;
		case R.id.btErase:
			if (erasemode == false) {
				erasemode = true;
				item.setTitle("Stop");
				imgView.setEraseMode(erasemode);
				// when editing all other functions to false
				// edit
				MenuItem EditBut = menu.findItem(R.id.btEdit);
				EditBut.setTitle("Edit");
				editmode = false;
				imgView.setEditMode(editmode);
				//
				// markers
				MenuItem MarkersBut = menu.findItem(R.id.btMarkers);
				MarkersBut.setTitle("Add markers");
				markersmode = false;
				imgView.setMarkersmode(markersmode);
				//

			} else {
				// alternate
				item.setTitle("Erase");
				erasemode = false;
				imgView.setEraseMode(erasemode);

			}
			break;
		case R.id.btMarkers:
			if (markersmode == false) {
				markersmode = true;
				item.setTitle("Stop");
				imgView.setMarkersmode(markersmode);
				// when editing all other functions to false
				// edit
				MenuItem EditBut = menu.findItem(R.id.btEdit);
				EditBut.setTitle("Edit");
				editmode = false;
				imgView.setEditMode(editmode);
				//
				// erase
				MenuItem EraseBut = menu.findItem(R.id.btErase);
				EraseBut.setTitle("Erase");
				erasemode = false;
				imgView.setEraseMode(erasemode);
				//

			} else {
				// alternate
				item.setTitle("Add markers");
				markersmode = false;
				imgView.setMarkersmode(markersmode);

			}
			break;
		case R.id.btConfirm:
			if (analysisorigin.equals("Protein")) {
				imgView.confirmation();
				// Intent returnActivity = new Intent(FullscreenActivity.this,
				// SegmentationActivity.class);
				Intent returnActivity = new Intent(FullscreenActivity.this,
						CompareActivity.class);
				// byte[] bytes;
				// bytes = compressImage(activeBmp);
				// returnActivity.putExtra("activeBmp", bytes);
				if (componentlist.size() != 0) {
					returnActivity.putExtra("componentlist", componentlist);
				}
				if (markerlist.size() != 0) {
					returnActivity.putExtra("markerlist", markerlist);
				}
				// byte[] bytes1;
				// bytes1 = compressImage(originalBmp);
				// returnActivity.putExtra("BMP", bytes1);
				returnActivity.putExtra("componentlist", componentlist);
				Collections.sort(markerlist,
						new Comparator<ConnectedComponent>() {
							@Override
							public int compare(ConnectedComponent cc1,
									ConnectedComponent cc2) {
								return cc1.top - cc2.top;
							}
						});
				returnActivity.putExtra("markerlist", markerlist);
				returnActivity.putExtra("origin", origin);

				// test
				returnActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

				finish();
				startActivity(returnActivity);
				break;
			}
			else
			{
				//do dna stuff here
				imgView.confirmation();
				Intent returnActivity = new Intent(FullscreenActivity.this,
						DNAValueActivity.class);
				if (componentlist.size() != 0) {
					returnActivity.putExtra("componentlist", componentlist);
					if (markerlist.size() != 0) {
						Collections.sort(markerlist,
								new Comparator<ConnectedComponent>() {
									@Override
									public int compare(ConnectedComponent cc1,
											ConnectedComponent cc2) {
										return cc1.top - cc2.top;
									}
								});
						returnActivity.putExtra("markerlist", markerlist);
						returnActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						finish();
						startActivity(returnActivity);
						break;
					}
					else
					{
						Toast.makeText(this, "No markers to compare", Toast.LENGTH_SHORT).show();
						break;
					}
				}
				else
				{
					Toast.makeText(this, "No fragments to calculate", Toast.LENGTH_SHORT).show();
					break;
				}
				
				
			}
		case R.id.btCancel:
			if (origin.equals("Segmentation")) {

				if (analysisorigin.equals("DNA")) {
					Intent returnActivity2 = new Intent(
							FullscreenActivity.this,
							DNASegmentationActivity.class);
					returnActivity2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

					finish();
					startActivity(returnActivity2);
					break;

				} else {
					Intent returnActivity2 = new Intent(
							FullscreenActivity.this, SegmentationActivity.class);
					returnActivity2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

					finish();
					startActivity(returnActivity2);
					break;
				}

			} else {
				Intent returnActivity2 = new Intent(FullscreenActivity.this,
						AutoActivity.class);
				startActivity(returnActivity2);
				break;
			}
		}

		return true;
	}

	@Override
	public void onBackPressed() {
		// startActivity(new Intent(FullscreenActivity.this,
		// SegmentationActivity.class));
		Intent returnActivity = new Intent(FullscreenActivity.this,
				SegmentationActivity.class);

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;
	}

}
